package org.qy.mongodb.server.service;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description:	des
 * @Author:		方宇康
 * @CreateDate:	2020/1/9 18:09
 * @Version:      	1.0.0.1
 * @Company:       联通智网科技有限公司
 */
@Slf4j
@Service
public class MongodbJdbcService
{
    private final MongoTemplate mongoClient;

    @Autowired
    public MongodbJdbcService(MongoTemplate mongoClient)
    {
        this.mongoClient = mongoClient;
    }

    /**
     * 数据库连接测试
     *
     * @param
     * @return
     * @exception
     * @date        2020/1/9 18:12
     */
    public void mongodbNoAutowired()
    {
        try {
            // 方式一
            ServerAddress serverAddress = new ServerAddress("106.12.175.83",27017);
            List<ServerAddress> serverAddressList = new ArrayList<>();
            serverAddressList.add(serverAddress);

            MongoCredential credential = MongoCredential.createCredential("test", "test", "mongodb".toCharArray());
            List<MongoCredential> credentials = new ArrayList<>();
            credentials.add(credential);

            //通过连接认证获取MongoDB连接
            MongoClient mongoClient = new MongoClient(serverAddressList, credentials);

            //连接到数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
            log.info("MongodbJdbcService|mongodbNoAutowired|Connect to database successfully");
            log.info("MongodbJdbcService|mongodbNoAutowired|连接到数据库：={}", mongoDatabase.getCollection("test"));

            // 方式二
            MongoClient mongoClientUrl = new MongoClient(new MongoClientURI("mongodb://test:mongodb@106.12.175.83:27017"));
            //连接到数据库
            mongoDatabase = mongoClientUrl.getDatabase("test");
            log.info("MongodbJdbcService|mongodbNoAutowired|Connect to database successfully");
            log.info("MongodbJdbcService|mongodbNoAutowired|连接到数据库：={}", mongoDatabase.getCollection("test"));
        } catch (Exception e) {
            log.error( "MongodbJdbcService|mongodbNoAutowired|数据库连接测试异常：={}", e.getClass().getName() + ": " + e.getMessage() );
        }
    }

    /**
     * 使用注解连接MongoDB
     *
     * @param
     * @return
     * @exception
     * @date        2020/1/9 18:12
     */
    public void mongodbAutowired()
    {
        MongoCollection<Document> people = this.mongoClient.getCollection("people");
        log.info("MongodbJdbcService|mongodbAutowired|集合大小：={}", people.count());
        if (Objects.isNull(people))
        {
            log.info("MongodbJdbcService|mongodbAutowired|集合大小为空");
            people = this.mongoClient.createCollection("people");
        }
        // 1.文档数据添加
        people.insertOne(new Document(){
            private static final long serialVersionUID = -4311920855372263692L;
            {
                put("1", "Java是世界上最好的编程语言");
                put("2", "Java开发都是直男");
            }
        });

        // 2.文档数据查询
        FindIterable<Document> findIterable = people.find();
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        while(mongoCursor.hasNext())
        {
            log.info("MongodbJdbcService|mongodbAutowired|使用注解连接MongoDB|文档数据查询|请求出参：={}", mongoCursor.next());
        }

        // 3.文档数据更新
        people.updateMany(Filters.eq("2", "Java开发都是直男"), new Document("$set",new Document("2", "Java开发都是直男，所以光棍")));
        findIterable = people.find();
        mongoCursor = findIterable.iterator();
        while(mongoCursor.hasNext())
        {
            log.info("MongodbJdbcService|mongodbAutowired|使用注解连接MongoDB|文档数据更新，数据查询|请求出参：={}", mongoCursor.next());
        }

        // 4.根据条件删除文档数据
        people.deleteOne(Filters.eq("_id", new ObjectId("5e1bd96796207e2910f5878b")));
        findIterable = people.find();
        mongoCursor = findIterable.iterator();
        while(mongoCursor.hasNext())
        {
            log.info("MongodbJdbcService|mongodbAutowired|使用注解连接MongoDB|根据条件删除文档数据，数据查询|请求出参：={}", mongoCursor.next());
        }

        // 5.后续相关操作详见Csdn博客：https://qy-bb.blog.csdn.net/article/details/103922070
    }
}
